﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIFrameAnimate : MonoBehaviour
{
    [System.Serializable]
    public class AniData
    {
        public string name;
        public Sprite[] sprites;
        public float speed = 1.0f;
        public bool loop = true;
    }

    public AniData[] aniDataList;

    private float timer = 0;
    private int curFrameIndex = 0;
    public AniData curAniData;

#if UNITY_EDITOR
    private void OnValidate()
    {
        this._aniIndex = Mathf.Clamp(this._aniIndex, 0, this.aniDataList.Length - 1);
        this.SetAnimation(this._aniIndex);
    }
#endif

    public int _aniIndex = 0;

    /// <summary>
    /// 设置当前的动画序号
    /// </summary>
    /// <value></value>
    public int aniIndex
    {
        get => _aniIndex;
        set
        {
            if (_aniIndex != value)
            {
                _aniIndex = value;
                this.SetAnimation(_aniIndex);
            }
        }
    }

    [HideInInspector]
    public string _aniName = "";
    /// <summary>
    /// 设置当前的动画名
    /// </summary>
    /// <value></value>
    public string aniName
    {
        get { return _aniName; }
        set
        {
            if (value != _aniName)
            {
                _aniName = value;
                for (int i = 0; i < this.aniDataList.Length; i++)
                {
                    if (_aniName == this.aniDataList[i].name)
                    {
                        this.aniIndex = i;
                        break;
                    }
                }
            }

        }
    }



    // Start is called before the first frame update
    void Awake()
    {
        this.aniIndex = this._aniIndex;
    }

    void SetAnimation(string name)
    {
        if (name != _aniName)
        {
            _aniName = name;
            for (int i = 0; i < this.aniDataList.Length; i++)
            {
                if (_aniName == this.aniDataList[i].name)
                {
                    this.aniIndex = i;
                    break;
                }
            }
        }
    }

    void SetAnimation(int index)
    {
        index = Mathf.Clamp(index, 0, aniDataList.Length - 1);
        curAniData = aniDataList[index];
        _aniName = curAniData.name;
        this.UpdateFrame();
    }

    void UpdateFrame()
    {
        int id = this.curFrameIndex;
        if (this.curAniData.sprites.Length <= 0) return;
        id = id % this.curAniData.sprites.Length;
        Sprite sprite = null;
        if (id < this.curAniData.sprites.Length) sprite = this.curAniData.sprites[id];
        this.GetComponent<Image>().sprite = sprite;
    }


    // Update is called once per frame
    void Update()
    {
        timer += Time.deltaTime;
        if (timer >= this.curAniData.speed)
        {
            timer = 0;
            timer = 0;
            this.curFrameIndex++;
            this.UpdateFrame();
        }


    }
}
